#include "defectinfo.h"

#include <QMainWindow>
#include <QWidget>

DefectInfo::DefectInfo() {}

DefectInfo::DefectInfo(const DefectInfo &other)
{
    SetType(other.type);
    SetRange(other.range);
}

DefectInfo::~DefectInfo() {}

void DefectInfo::SetType(QString type)
{
    this->type = type;
}

void DefectInfo::SetRange(QRectF rect)
{
    this->range = rect;
}

QString DefectInfo::GetType()
{
    return type;
}

QRectF DefectInfo::GetRange()
{
    return range;
}

DefectInfo &DefectInfo::operator=(const DefectInfo &other)
{
    this->type = other.type;
    this->range = other.range;
    return *this;
}

QString DefectInfo::toJson()
{
    QJsonObject rangeObject;
    rangeObject.insert(QStringLiteral("x"), range.x());
    rangeObject.insert(QStringLiteral("y"), range.y());
    rangeObject.insert(QStringLiteral("w"), range.width());
    rangeObject.insert(QStringLiteral("h"), range.height());

    QJsonObject defectInfoObject;
    defectInfoObject.insert(QStringLiteral("type"), type);
    defectInfoObject.insert(QStringLiteral("range"), rangeObject);
    return QString(QJsonDocument(defectInfoObject).toJson(QJsonDocument::Compact));
}

bool DefectInfo::FromJson(QJsonObject defectInfoObject)
{
    type = defectInfoObject.value("type").toString();
    QJsonObject rangeObject = defectInfoObject.value("range").toObject();
    range.setX(rangeObject.value("x").toDouble());
    range.setY(rangeObject.value("y").toDouble());
    range.setWidth(rangeObject.value("w").toDouble());
    range.setHeight(rangeObject.value("h").toDouble());
    return true;
}

bool DefectInfo::FromJson(QJsonValue jsonValue)
{
    QJsonParseError result;
    QString str = jsonValue.toString();
    QByteArray jsonByteArray = str.toUtf8();

    QJsonDocument defectInfoRoot = QJsonDocument::fromJson(jsonByteArray, &result);
    if (result.error != QJsonParseError::NoError) {
        return false;
    }

    QJsonObject defectInfoObject = defectInfoRoot.object();
    return FromJson(defectInfoObject);
}

void DefectInfo::test()
{
    QString str = toJson();

    FromJson(str);
}
